<template>
  <el-card class="box-card">
    <template #header>
      <div class="card-header">
        <span>{{ $route.query.type == "add" ? '新建社科基金填报' : "编辑社科基金填报" }}</span>
        <el-button type="primary" :loading="buttonLoading" @click="goList">退出</el-button>
      </div>
    </template>

    <div class="add-form" v-loading="loading">
      <el-form
        ref="ruleFormRef"
        :model="ruleForm"
        :rules="rules"
        label-width="140px"
        class="demo-ruleForm"
        status-icon
      >
        <el-form-item label="项目名称" prop="name">
          <el-input v-model="ruleForm.name" placeholder="请输入项目名称"></el-input>
        </el-form-item>

        <el-form-item label="项目负责人" prop="projectLeader">
          <el-input v-model="ruleForm.projectLeader" placeholder="请输入项目负责人"></el-input>
        </el-form-item>

        <el-form-item label="成果形式" prop="achievementForm">
          <el-select v-model="ruleForm.achievementForm" placeholder="请选择成果形式">
            <el-option label="专著或论文" value="1" />
            <el-option label="研究报告" value="2" />
          </el-select>
        </el-form-item>

        <el-form-item label="填表日期" prop="fillTime">
          <el-date-picker
            v-model="ruleForm.fillTime"
            type="date"
            placeholder="请选择填表日期"
            value-format="YYYY-MM-DD"
            clearable
            :disabled-date="disabledDate"
          />
        </el-form-item>

        <el-form-item label="负责人所在单位" prop="unit">
          <el-input v-model="ruleForm.unit" placeholder="请输入负责人所在单位"></el-input>
        </el-form-item>

        <el-form-item label="主要参加者" prop="persons">
          <el-input v-model="ruleForm.persons" placeholder="请输入主要参加者"></el-input>
        </el-form-item>

        <el-form-item label="附件" prop="files">
          <upload-file-result :fileList="fileList" />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="uploadEvent">
            <el-icon>
              <UploadFilled />
            </el-icon>
            上传附件
          </el-button>
          <span style="margin-left: 10px;">请上传不超过20M的文件，格式：jpg/jpeg/png/mp4/doc/docx/xls/xlsx/ppt/pptx/pdf</span>
        </el-form-item>
        
        <el-form-item class="add-button">
          <el-button type="primary" :loading="buttonLoading" @click="submitForm(ruleFormRef)">
            {{ $route.query.type == "add" ? '新增' : "编辑" }}
          </el-button>
          <el-button :loading="buttonLoading" @click="resetForm(ruleFormRef)">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
  </el-card>
</template>

<script>
export default { name: 'backendLearnfundAdd' }
</script>

<script setup>
import { ref, reactive, onMounted, watch } from 'vue';
import { useRouter } from 'vue-router'
import { UploadFilled } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { http } from '@/utils/http/index';
import { format } from '@/plugins/moment.js'
import { uploadFile } from '@/utils/file.js'
import { testFileType, testFileSize, isJsonString } from '@/utils/backend.js'
import { useAuthStore } from '@/stores/modules/auth.js';
import uploadFileResult from "@/components/backend/fileList.vue"

/* 路由 */
const route = useRouter()

/* 用户信息 */
const authStore = useAuthStore()

onMounted(() => {
  /* 如果是编辑，查询详情填充表单项 */
  if(route.currentRoute.value.query.id){
    getFundDetail()
  }
})

/* 详情数据加载动画 */
const loading = ref(false)

/* 查询详情 */
const getFundDetail = () => {
  loading.value = true
  http.$GET("/DeclarationM/GetSocialScienceFundDetailById", { Id: route.currentRoute.value.query.id }).then(res => {
    loading.value = false
    if (res.isError) return
    if (!res.result) return

    /* 赋值 */
    Object.keys(ruleForm.value).forEach((key)=>{
      if(res.result[key] != null){
        ruleForm.value[key] = res.result[key];
      }
    })

    /* 处理学习日期 */
    ruleForm.value.fillTime = format(res.result.fillTime)

    /* 附件 */
    if(!isJsonString(res.result.files)){
      fileList.value = []
      ruleForm.value.files = ""
      return
    }
    if(res.result.files != ''){
      let fileName = JSON.parse(res.result.files)

      if(fileName.filePathArray){
        fileList.value = fileName.filePathArray
      }else{
        fileList.value = []
        ruleForm.value.files = ""
      }
    }
  }).catch(err => {
    loading.value = false
    ElMessage.warning("查询失败")
  })
}

/* 日期禁选范围 */
const disabledDate = (time) => {
  return time.getTime() < new Date() - 24 * 60 * 60 * 1000
}

/* 新增、编辑表单 */
const ruleFormRef = ref(null)

/* 新增、编辑表单值 */
const ruleForm = ref({
  id: "",
  name: "",
  fillingTypeName: "社科基金申报",
  achievementForm: "",
  projectLeader: null,
  unit: "",
  fillTime: "",
  persons: "",
  files: "",
})

/* 附件列表 */
const fileList = ref([])
/* 是否有上传附件 */
const isUploadFile = ref(false)

/* 校验附件规则 */
const checkFile = (rule, value, callback) => {
  if (ruleForm.value.files.length == 0) {
    callback(new Error('请上传附件'))
  } else {
    callback()
  }
}

/* 表单校验规则 */
const rules = reactive({
  name: [
    { required: true, message: '请填写项目名称', trigger: 'change' },
    { max: 255, message: '不能输入超过255个字符', trigger: 'blur'}
  ],
  achievementForm: [
    { required: true, message: '请选择成果形式', trigger: 'change' }
  ],
  projectLeader: [
    { required: true, message: '请输入项目负责人', trigger: 'change' },
    { max: 255, message: '不能输入超过255个字符', trigger: 'blur'}
  ],
  unit: [
    { required: true, message: '请输入负责人所在单位', trigger: 'change' },
    { max: 255, message: '不能输入超过255个字符', trigger: 'blur'}
  ],
  fillTime: [
    { required: true, message: '请选择填表日期', trigger: 'change' }
  ],
  persons: [
    { required: true, message: '请输入主要参加者', trigger: 'change' },
    { max: 255, message: '不能输入超过255个字符', trigger: 'blur'}
  ],
})

/* 点击上传文件 */
const uploadEvent = () => {
  /* 文件上传类型 */
  let fileType = ".jpg,.jpeg,.png,.JPG,.JPEG,.PNG,.mp4,.MP4,.doc,.docx,.xls,.xlsx,.ppt,.pptx,.pdf,.DOC,.DOCX,.XLS,.XLSX,.PPT,.PPTX,.PDF"

  uploadFile({ accept: fileType, multiple: true }).then(res => {
    /* 文件格式判断 */
    if(!testFileType(res, /^(jpg|jpeg|png|JPG|JPEG|PNG|mp4|MP4|doc|docx|xls|png|xlsx|ppt|pptx|pdf|DOC|DOCX|XLS|XLSX|PPT|PPTX|PDF)$/)){
      ruleForm.value.files = null
      fileList.value = []
      isUploadFile.value = false
      return 
    }

    /* 文件大小判断 */
    if(!testFileSize(res, 10*1024*1024)){
      ruleForm.value.files = null
      fileList.value = []
      isUploadFile.value = false
      return 
    }

    console.log(res, "文件上传成功")
    if(res){
      isUploadFile.value = true
      ruleForm.value.files = res
      /* 上传成功后清除校验 */
      ruleFormRef.value.clearValidate("files")
      /* 文件列表 */
      fileList.value = res
    }
  })
}

/* 提交新增或编辑时，按钮禁用 */
const buttonLoading = ref(false)

/* 提交新增、编辑 */
const submitForm = (formName) => {
  ruleFormRef.value.validate((valid, fields) => {
    if(valid) {
      buttonLoading.value = true

      /* 新增时不传id */
      if(route.currentRoute.value.query.type == 'add'){
        delete ruleForm.value.id
      }

      /* 未更新附件时不传值 */
      if(!isUploadFile.value) {
        delete ruleForm.value.files
      }

      /* 参数处理 */
      const formData = new FormData();

      for(let k in ruleForm.value){
        if(isUploadFile.value){
          if(k == 'files'){
            for(let j in ruleForm.value[k]){
              if(j < ruleForm.value[k].length){
                formData.append(k, ruleForm.value[k][j]);
              }
            }
          }else{
            formData.append(k, ruleForm.value[k]);
          }
        }else{
          formData.append(k, ruleForm.value[k]);
        }
      }

      if(authStore.auth_token){
        formData.append('authToken', authStore.auth_token)
      }

      http.$POST("/DeclarationM/AddOrUpdateSocialScienceFund", formData).then(res => {
        buttonLoading.value = false
        if (res.IsError) {
          ElMessage({
            type: 'warning',
            message: '操作失败',
          })
        }else{
          ElMessage({
            type: 'success',
            message: '操作成功',
          })
          route.push({
            path: "/backend/learn-fund"
          })
        }
      }).catch(err => {
        buttonLoading.value = false
        ElMessage({
          type: 'warning',
          message: '操作失败',
        })
      })
    }else{
      ElMessage({
        type: 'warning',
        message: '请先完成必填项',
      })
    }
  })
}

/* 重置表单 */
const resetForm = (formName) => {
  ruleFormRef.value.resetFields()
  fileList.value = []
  isUploadFile.value = false
}

/* 返回列表 */
const goList = () => {
  route.push({
    path: "/backend/learn-fund",
    query: route.currentRoute.value.query.currentPage ? { currentPage: route.currentRoute.value.query.currentPage } : {}
  })
}
</script>

<style lang='scss' scoped>
@import "@/assets/styles/backendElement.scss";
</style>